import { useEffect, useMemo, useState } from 'react';
import { Card, Form, Row, Col, Select, DatePicker, Input, Button, Tabs, Table, Empty, Pagination, Modal } from 'antd';
import dayjs, { Dayjs } from 'dayjs';
import { getBindAll } from '../../services/login';
import { kefu1, kefu2 } from '../../assets/images/base64';

type RowType = {
  key: string;
  shopName: string;
  oid: string;
  itemPic: string;
  itemTitle: string;
  skuDesc: string;
  statusDesc: string;
  refundStatus: string;
};

export default function RefundList() {
  const [shopId, setShopId] = useState<string | undefined>(undefined);
  const [timeRange, setTimeRange] = useState<[Dayjs, Dayjs] | null>(null);
  const [oid, setOid] = useState('');
  const [title, setTitle] = useState('');
  const [status, setStatus] = useState<string>('1');
  const [data, setData] = useState<RowType[]>([]);
  const [pageNum, setPageNum] = useState<number>(1);
  const [pageSize, setPageSize] = useState<number>(10);
  const [total, setTotal] = useState<number>(0);
  const [loading, setLoading] = useState<boolean>(false);
  const [shopOptions, setShopOptions] = useState<{label:string,value:string}[]>([]);
  const [platformModalVisible, setPlatformModalVisible] = useState<boolean>(true);
  const [selectedPlatform, setSelectedPlatform] = useState<string>('');

  useEffect(() => {
    const start = dayjs().subtract(29, 'day').startOf('day');
    const end = dayjs().endOf('day');
    setTimeRange([start, end]);
    // 拉取店铺列表（测试请求是否带上 Header/Sign/Timestamp）
    (async () => {
      try {
        const res: { code: number; data: Array<{ shopName: string; shopId: number }> } = await getBindAll();
        if (res?.code === 200 && Array.isArray(res.data)) {
          setShopOptions(res.data.map((it) => ({ label: it.shopName, value: String(it.shopId) })));
        }
      } catch (e) {
        console.warn('getBindAll failed:', e);
      }
    })();
  }, []);

  const columns = useMemo(() => [
    {
      title: '订单号',
      dataIndex: 'oid',
      key: 'oid',
      width: '20%',
      render: (_: unknown, row: RowType) => (
        <div>
          <div>店铺名称：{row.shopName}</div>
          <div>店铺订单号：{row.oid}</div>
        </div>
      ),
    },
    {
      title: '订单商品',
      key: 'item',
      width: '50%',
      render: (_: unknown, row: RowType) => (
        <div style={{ display: 'flex', justifyContent: 'space-between' }}>
          <div style={{ width: '20%' }}>
            <img src={row.itemPic} style={{ width: 30, height: 30 }} />
          </div>
          <div style={{ width: '79%', textAlign: 'left' }}>
            <div>{row.itemTitle}</div>
            <div>SKU：{row.skuDesc}</div>
          </div>
        </div>
      ),
    },
    {
      title: '订单状态',
      key: 'status',
      width: '15%',
      render: (_: unknown, row: RowType) => (
        <div>
          <div>{row.statusDesc}</div>
          <div>{row.refundStatus}</div>
        </div>
      ),
    },
    {
      title: '操作',
      key: 'action',
      width: '15%',
      render: () => (
        <Button type="default">采购下单</Button>
      ),
    },
  ], []);

  const refresh = () => {
    setLoading(true);
    // TODO: 请求数据
    setData([]);
    setTotal(0);
    setLoading(false);
  };

  const handlePlatformConfirm = () => {
    if (!selectedPlatform) {
      return;
    }
    setPlatformModalVisible(false);
    // 这里可以根据选择的平台进行相应处理
    console.log('选择的平台:', selectedPlatform);
  };

  return (
    <div className="refund-list-page">
      <Card style={{ marginBottom: 8 }}>
        <Form layout="vertical">
          <Row gutter={16}>
            <Col span={8}>
              <Form.Item label="来源店铺">
                <Select allowClear placeholder="请选择一个店铺" value={shopId} onChange={setShopId} options={shopOptions} />
              </Form.Item>
            </Col>
            <Col span={9}>
              <Form.Item label="成交时间">
                <DatePicker.RangePicker
                  showTime
                  value={timeRange}
                  onChange={(v) => setTimeRange(v as [Dayjs, Dayjs] | null)}
                />
              </Form.Item>
            </Col>
            <Col span={7}>
              <Form.Item label="卖出单号">
                <Input placeholder="请输入订单号" value={oid} onChange={(e) => setOid(e.target.value)} />
              </Form.Item>
            </Col>
          </Row>
          <Row gutter={16}>
            <Col span={8}>
              <Form.Item label="商品标题">
                <Input placeholder="请输入商品标题" value={title} onChange={(e) => setTitle(e.target.value)} />
              </Form.Item>
            </Col>
            <Col span={8} style={{ display: 'flex', alignItems: 'flex-end' }}>
              <Form.Item>
                <Button type="primary" onClick={refresh}>查询</Button>
              </Form.Item>
            </Col>
            <Col span={8} />
          </Row>
        </Form>
      </Card>

      <Card>
        <Tabs activeKey={status} onChange={setStatus}
          items={[
            { key: '1', label: '待处理' },
            { key: '2', label: '待退货' },
            { key: '3', label: '待收货' },
            { key: '4', label: '已拒绝' },
            { key: '5', label: '退款成功' },
            { key: '6', label: '退款失败' },
            { key: '0', label: '全部' },
          ]}
        />
        <Table
          dataSource={data}
          columns={columns}
          pagination={false}
          loading={loading}
          locale={{ emptyText: <Empty description="暂无数据" /> }}
          scroll={{ y: 480 }}
          rowKey="key"
        />
        <div style={{ marginTop: 8, textAlign: 'right' }}>
          <Pagination
            size="small"
            showSizeChanger
            pageSizeOptions={[20, 50, 100, 200]}
            current={pageNum}
            pageSize={pageSize}
            total={total}
            onChange={(p) => setPageNum(p)}
            onShowSizeChange={(_, s) => setPageSize(s)}
          />
        </div>
      </Card>

      {/* 平台选择弹窗 */}
      <Modal
        title="请选择使用平台"
        open={platformModalVisible}
        closable={false}
        maskClosable={false}
        footer={[
          <Button 
            key="confirm" 
            type="primary" 
            onClick={handlePlatformConfirm}
            disabled={!selectedPlatform}
          >
            确定
          </Button>
        ]}
        width={400}
      >
        <div style={{ textAlign: 'center', padding: '20px 0' }}>
          <div style={{ display: 'flex', justifyContent: 'center', gap: '40px', marginBottom: '20px' }}>
            {/* 快手选项 */}
            <div 
              style={{ 
                cursor: 'pointer',
                padding: '20px',
                border: selectedPlatform === 'kuaishou' ? '2px solid #ff6900' : '2px solid #e8e8e8',
                borderRadius: '8px',
                backgroundColor: selectedPlatform === 'kuaishou' ? '#fff7e6' : '#fff',
                transition: 'all 0.3s'
              }}
              onClick={() => setSelectedPlatform('kuaishou')}
            >
              <img 
                src={kefu1} 
                alt="快手" 
                style={{ width: '60px', height: '60px', marginBottom: '10px' }}
              />
              <div style={{ fontSize: '16px', fontWeight: 'bold', color: '#333' }}>
                快手
              </div>
            </div>

            {/* 抖音选项 */}
            <div 
              style={{ 
                cursor: 'pointer',
                padding: '20px',
                border: selectedPlatform === 'doudian' ? '2px solid #ff6900' : '2px solid #e8e8e8',
                borderRadius: '8px',
                backgroundColor: selectedPlatform === 'doudian' ? '#fff7e6' : '#fff',
                transition: 'all 0.3s'
              }}
              onClick={() => setSelectedPlatform('doudian')}
            >
              <img 
                src={kefu2} 
                alt="抖音" 
                style={{ width: '60px', height: '60px', marginBottom: '10px' }}
              />
              <div style={{ fontSize: '16px', fontWeight: 'bold', color: '#333' }}>
                抖音
              </div>
            </div>
          </div>
        </div>
      </Modal>
    </div>
  );
}


